﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Tizer.Core.Repository;
using Tizer.Web.Backoffice.Controls;
using Tizer.Web.Helper;

namespace Tizer.Web.Backoffice
{
    /// <summary>
    /// Редактирование валюты
    /// </summary>
    public partial class CurrencyEdit : AdminBasePage
    {
        /// <summary>
        /// Загрузка страницы
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            this.SetPageTitle();
            if (!Page.IsPostBack)
            {
                var id = QueryHelper.Value<int>("id", 0);
                if (id == 0)
                    Response.Redirect(UrlAdminDashboard);
                else
                {
                    using (var currencyRepository = new CurrencyRepository())
                    {
                        var currency = currencyRepository.GetById(id);
                        if (currency != null)
                        {
                            txtName.Text = currency.Name;
                            txtCode.Text = currency.Code;
                        }
                        else
                            Response.Redirect(UrlAdminDashboard);
                    }
                }
            }
        }

        /// <summary>
        /// Сохранение данных
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Edit(object sender, EventArgs e)
        {
            var id = QueryHelper.Value<int>("id", 0);
            if (id == 0)
                Response.Redirect(UrlAdminDashboard);
            else
            {
                using (var currencyRepository = new CurrencyRepository())
                {
                    var currency = currencyRepository.GetById(id);
                    if (currency != null)
                    {
                        if (!string.IsNullOrEmpty(txtName.Text))
                        {
                            currency.Name = txtName.Text;
                            currency.Code = txtCode.Text;

                            currencyRepository.SaveChanges();
                            Response.Redirect(UrlAdminCurrencyList);
                        }
                    }
                }
            }
            tizerMessage.SetMessage("Ошибка", "Невозможно обновить валюту", MessageType.Error);
        }
    }
}